package org.activequant.math.algorithms;

import org.activequant.core.domainmodel.data.TradeIndicationSeries;

/**
 * This VWAP class can compute a volume weighted average price. <br>
 *<br>
 * - [21.07.2008] Created (Ulrich Staudinger)<br>
 * 
 * 
 * @author ustaudinger
 */
public class VWAP {

	/**
	 * computes vwap based on trade indication series. Delegates to double[] method. <br/>
	 * returns the VWAP (volume weighted average price) for the tradeIndicationPrices(double[]) and tradeIndicationQuantities(double[]) of the given tis(TradeIndicationSeries)<br/>
	 * <strong>VWAP=(quantity1*price1 + quantity2*price2+...+quantityN*priceN)/totalQuantity</strong>
	 * @param tis
	 */
	public static double compute(TradeIndicationSeries tis) {
		double[] prices = tis.getTradeIndicationPrices();
		double[] volumes = tis.getTradeIndicationQuantities();
		// hand on . 
		return compute(prices, volumes);
	}

	/**
	 * computes vwap based on double arrays. <br/>
	 * returns the VWAP (volume weighted average price) for the given prices(double[]) and quantities(double[])
	 * <strong>VWAP=(quantity1*price1 + quantity2*price2+...+quantityN*priceN)/totalQuantity</strong>
	 * @param prices
	 * @param quantities
	 * @return
	 */
	public static double compute(double[] prices, double[] quantities) {
		// sanity check.
		if(prices.length!=quantities.length)throw new RuntimeException("Input arrays don't have equal length.");
		
		// get the total quantity
		double vol = 0.0;
		for (double q : quantities)vol+=q;
		
		// compute volume weighted price. 
		double price = 0.0;
		for(int i=0;i<prices.length;i++){
			price += (quantities[i]/vol * prices[i]);
		}
		// leave. 
		return price; 
	}

}
